package com.example.webflux_mongo.controller;

import com.example.webflux_mongo.bean.User;
import com.example.webflux_mongo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;

/**
 * Copyright(C), 2020-2021, AmbroseCdMeng
 * FileName:    UserController
 * Author:      AmbroseCdMeng
 * Date:        2021/1/1617:34
 * Description: 用户控制器。编写 CRUD 接口
 * History:
 * <author>     <time>      <version>       <desc>
 * 作者姓名     修改时间        版本号           描述
 */
@RestController
@RequestMapping(path = "/user")
public class UserController {
    @Autowired
    private UserRepository userRepository;

    @GetMapping(value = "/list")
    public Flux<User> getAll(){
        return userRepository.findAll();
    }

    /**
     * 测试会发现，查询结果是一个一个返回的，而不是一次性返回全部
     * @return
     */
    @GetMapping(value = "/listdelay", produces = MediaType.APPLICATION_STREAM_JSON_VALUE)
    public Flux<User> getAlldelay(){
        return userRepository.findAll().delayElements(Duration.ofSeconds(1));
    }

    @GetMapping("/{id}")
    public Mono<ResponseEntity<User>> getUser(@PathVariable String id){
        return userRepository.findById(id).map(getUser -> ResponseEntity.ok(getUser))
                .defaultIfEmpty(ResponseEntity.notFound().build());
    }

    @PostMapping("")
    public Mono<User> createUser(User user){
        return userRepository.save(user);
    }

    @PutMapping("/{id}")
    public Mono updateUser(@PathVariable(value = "id") String id, User user){
        return userRepository.findById(id).flatMap(
                exist -> {
                    exist.setName(user.getName());
                    return userRepository.save(exist);
                }).map(update -> new ResponseEntity<>(update, HttpStatus.OK))
                .defaultIfEmpty(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    @DeleteMapping("/{id}")
    public Mono<ResponseEntity<Void>> deleteUser(@PathVariable(value = "id") String id){
        return userRepository.findById(id)
                .flatMap(exist -> userRepository.delete(exist)
                .then(Mono.just(new ResponseEntity<Void>(HttpStatus.OK))))
                .defaultIfEmpty(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }



}
